<?php
/* CONFIG.INC.PHP by martin $ 2009/12/25 16:00:07
*/

checkADMIN();

if($SESSION->owner() != ONAME) _header('admin.php?mode=article');

$ini_file = OD.'ini.inc.php';
$theme_ini = OD.'theme.ini.php';
$mob_ini = OD.'mob.ini.php';
$header = $body = $cfg_end = '';
$valid = TRUE;

if(p_('configs') != ''){ // CONFIGURATION
 $new_ini_lines = array();
 $ini_lines = explode("\n",get_file_content($ini_file));
 foreach ($ini_lines as $i=>$line){
  if(strstr($line,'?>')){ $new_ini_lines[] = '?>'; break;}
  if(preg_match("{MAX_ISIZE','(\d+)'}", $line, $sz)) $orgISIZE = $sz[1];
  if(preg_match("{OWNER','(.+?)'}", $line, $ow)) $orgOWNER = $ow[1];
  if(preg_match("{OPASS','(.+?)'}", $line, $op)) $orgOPASS = $op[1];
  if(preg_match("{ALIAS','(.*?)'}", $line, $oa)) $orgALIAS = $oa[1];
  if(preg_match("{MODE_STATIC','(.*?)'}", $line, $om)) $orgMODE = $om[1];
  if(strstr($line, '/*[/config]*/')) $cfg_end = $i;
  if(!$cfg_end && preg_match("{^(define\('.+?',)'.*?'(\); +?/\*.*?[#$]? ?\*/)}", $line, $desc)){
   $new_val = MAGIC_QUOTES ? stripslashes($_POST['configs'][$i]) : $_POST['configs'][$i];
   $new_val = ($mb) ? @mb_convert_kana($new_val, 'n') : $new_val;
   $new_val = trim(htmlspecialchars($new_val, ENT_QUOTES)); // single quote to &#039;
   if(strpos($desc[1], 'OWNER')){
    $newOWNER = $new_val;
    if(!preg_match("{^[[:alnum:]]+$}i", $newOWNER)){
     $valid = FALSE;
     showMessage('ID名に英数字以外が含まれています');
    }
   }
   if(strpos($desc[1], 'OPASS')){
    $newOPASS = $new_val;
    if(!preg_match("{^[[:alnum:]]+$}i", $newOPASS)){
     $valid = FALSE;
     showMessage('PWDに英数字以外が含まれています');
    }
   }
   if(strpos($desc[1], 'TAG_MIN_FONT_SIZE') || strstr($desc[1], 'TAG_MIN_FONT_SIZE')){
    if(!preg_match("{^\d+$}i", $new_val)){
     $valid = FALSE;
     showMessage('「タグの文字サイズ」関連に数字以外が含まれています');
    }
   }
   if(strpos($desc[1], 'ALIAS')) $newALIAS = $new_val;
   if(strpos($desc[1], 'SEE_CAT_HIERARCHY')) $newCATHIER = $new_val;
   if(strpos($desc[1], 'ENABLE_AUTO_MOBCHK')) $newMOBCHK = $new_val;
   if(strpos($desc[1], 'MAX_ISIZE')) $newISIZE = $new_val;
   $new_ini_lines[] = $desc[1]."'".$new_val."'".$desc[2];
  } else $new_ini_lines[] = $line;
 }
 if($valid){
  rewrite($ini_file, $new_ini_lines);
  include ($mob_ini); # get::$MOB_CFG
  $MOB_CFG[11] = $newMOBCHK;
  rewrite_ini($mob_ini, $MOB_CFG);
 }
 $newONAME = $newALIAS=='' ? $newOWNER : $newALIAS;
 if($valid &&  (ONAME != $newONAME)){
  replace_log_by_target('|'.ONAME.'|', "|$newONAME|"); // ログの投稿名も修正
  replace_log_by_target('|'.ONAME.'|', "|$newONAME|", CMT_DIR); // コメントログの投稿名も修正
  update_cache(array('recent_comments'), '', $newONAME);
  $SESSION->destroy();
  showMessage('投稿ネームを作成/変更しました。再度ログインしなおします･･･');
  return $DIVISION['body'] .= $header.'<script type="text/javascript">setTimeout(\'window.location="admin.php?mode=login"\',2500);</script>';
 }
 if($valid && ($orgOWNER != $newOWNER || $orgOPASS != $newOPASS)){ # OWNER,OPASS に変更があれば
  $newONAME = $newALIAS=='' ? $newOWNER : $newALIAS;
  replace_log_by_target('|'.ONAME.'|', "|$newONAME|"); // ログの投稿名も修正
  replace_log_by_target('|'.ONAME.'|', "|$newONAME|", CMT_DIR); // コメントログの投稿名も修正
  update_cache(array('recent_comments'), '', $newALIAS);
  $SESSION->destroy();
  showMessage('ID名 or PWDを変更しました。再度ログインしなおします･･･');
  return $DIVISION['body'] .= $header.'<script type="text/javascript">setTimeout(\'window.location="admin.php?mode=login"\',2500);</script>';
 }
 if($valid && (SEE_CAT_HIERARCHY != $newCATHIER)) unlink(PATH.DB.'cache.db');
 if($valid && ($orgISIZE != $newISIZE) && ($orgISIZE > $newISIZE)){ # MAX_ISIZE が替わっていれば
  $logfiles = my_glob('2', LOG);
  foreach ($logfiles as $i=>$log){
   $new_log = array();
   $flag = FALSE;
   $logline = file($log);
   foreach ($logline as $line){
    if(preg_match_all('{<img .*?src="([^"]*?)"([^>]*?)/?>}i', $line, $mt)){ // icluding image-tags
     foreach ($mt[1] as $j=>$imgf){
      if(preg_match('{<img src="'.$imgf.'" alt="([^:]+?):(\d+?):(\d+?):(\d+?):(\d+?):([^"]+?)" ?/>}', $mt[0][$j], $m)){
       if(strstr($mt[0][$j], 'http://')) continue; # amazon etc.
       $ratio = $newISIZE / max($m[2], $m[3]);
       if($ratio < 1 && GD==TRUE){
        $tw = round($m[2]*$ratio); $th = round($m[3]*$ratio);
        $new_img = "<img src=\"$imgf\" alt=\"$m[1]:$m[2]:$m[3]:$tw:$th:$m[6]\"/>";
        $line = str_replace($mt[0][$j], $new_img, $line);
        if(is_file($tif=str_replace(IMG_DIR, IMG_DIR.THUMB2, $imgf))) unlink($tif);
        if(is_file($imgf) && GD) create_thumbnail($imgf, $tif, $m[2], $m[3], $ratio);
       } else {
        $new_img = "<img src=\"$imgf\" alt=\"$m[1]:$m[2]:$m[3]:0:0:$m[6]\"/>";
        $line = str_replace($mt[0][$j], $new_img, $line);
        if(is_file($tif=str_replace(IMG_DIR, IMG_DIR.THUMB2, $mt[0][$j]))) unlink($tif);
       }
       $flag = TRUE;
      } # if
     } # foreach 3
    }
    $new_log[] = $line;
   } # foreach 2
   if($flag==true) rewrite($log, $new_log);
  } # foreach 1
  if(GD==true) showMessage('画像のリサイズを実行しました');
 } # if
 $mode_static = preg_replace("{^.+?MODE_STATIC','(0|1)'.+$}", '\\1', $new_ini_lines[8]);

 if(is_numeric($mode_static) && $orgMODE != $mode_static){ # 静的出力の処理
  $cmd = 'RewriteEngine on'.NL
       . 'RewriteRule ^pages/(.+)/$ index.php?path=pages/$1 [L]'.NL
       . "RewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\n"
       . 'RewriteRule ^(.*)$ index.php?path=$1 [L]'.NL;
  $hta = PATH.'.htaccess';
  if(is_file($hta)){
   $_hta = trim(preg_replace('#RewriteEngine on.+?(view=\$4|path=\$1) \[L\]#ms', '', get_file_content($hta)));
   if(!$mode_static){
    if(empty($_hta)) @unlink($hta); else rewrite($hta, $_hta);
   } else rewrite($hta, $cmd.$_hta."\r\n");
  } else rewrite($hta, $cmd);
  unlink(PATH.DB.'cache.db');
  foreach (my_glob('box1.db', DB) as $cal) unlink(PATH.$cal);
  foreach (my_glob('box2.db', DB) as $cal) unlink(PATH.$cal);
  foreach (my_glob('line1.db', DB) as $cal) unlink(PATH.$cal);
  foreach (my_glob('line2.db', DB) as $cal) unlink(PATH.$cal);
 }
 if($valid) showMessage(' 更新しました ');
}

if(v_('sub')=='detail' || v_('sub')==''){ // Default View
 include ($theme_ini);
 $body .= '
 <form action="admin.php" method="post">
 <fieldset>
 <legend> 環境設定 </legend>
  <p class="center" style="margin: 1em auto;">
  <input type="image" src="Images/reload1.png" title="更 新"
    onmouseover="this.src=\'Images/reload2.png\';"
    onmouseout="this.src=\'Images/reload1.png\'" alt="Refresh" />
  </p>
  <div class="hidden">
   <input type="hidden" name="mode" value="config" />
   <input type="hidden" name="sub" value="detail" />
  </div>
 ';

 $_configs = explode("\n",get_file_content($ini_file));
 $body .= '
  <table style="font-size:95%; background:#f2f1f5; width: 99.9%; margin: auto;">
 ';
 $cfg_start = $cfg_end = 0;
 
 foreach($_configs as $i => $v){
  if(strstr($v, '/*[config]*/')){
   $cfg_start = ($i+1);
   continue;
  }
  if(strstr($v, '/*[/config]*/')){
   $cfg_end = $i;
   break;
  }
  
  $bgc = ($i%2==1) ? '' : 'style="background:#fff;"';
  if(strstr($v, 'define') && !$cfg_end){
   // $desc[1]: define, $desc[2]: value, $desc[3]: description
   preg_match("{^define\('(.+?)','?(.*?)'?\);\s+/\*(.*?)[#$]? ?\*/}", $v, $desc);
   if(strstr($v, '# ')){ // radio button mode
    $body .= '<tr '.$bgc.'><td class="right">'.$desc[3].'::</td>';
    if($desc[2]==1){
     $body .= '<td>&nbsp;&nbsp;<input type="radio" id="r1'.$i.'" checked="checked" name="configs['.$i.']" value="1" /><label for="r1'.$i.'">する</label>&nbsp; <input type="radio" id="r0'.$i.'" name="configs['.$i.']" value="0" /><label for="r0'.$i.'">しない</label></td>';
    } else {
     $body .= '<td>&nbsp;&nbsp;<input type="radio" id="r1'.$i.'" name="configs['.$i.']" value="1" /><label for="r1'.$i.'">する</label>&nbsp; <input type="radio" id="r0'.$i.'" name="configs['.$i.']" checked="checked" value="0" /><label for="r0'.$i.'">しない</label></td>';
    }
    $body .= '</tr>'.NL;
   } elseif(strstr($v, '$ ')){ // selectbox mode
    $body .= '<tr '.$bgc.'><td class="right">'.$desc[3].'::</td>';
    $body .= '<td>&nbsp;&nbsp;<select name="configs['.$i.']" onchange="this.blur();">'.NL;
    foreach (array('left'=>'左寄せ','center'=>'センタリング','right'=>'右寄せ','none'=>'なし') as $k=>$v){
     $selected = ($desc[2]==$k) ? ' selected="selected"' : '';
     $body .= '<option value="'.$k.'"'.$selected.'>■ '.$v.'</option>'.NL;
    }
    $body .= NL.'</select></td></tr>'.NL;
   } else {
    $body .= '<tr '.$bgc.'><td class="right">'.$desc[3].'::</td>';
    $body .= '<td><input type="text" name="configs['.$i.']" style="font:500 15px arial;" value="'.$desc[2].'" /></td></tr>'.NL;
   }
  }
  if(preg_match('{^\/\*\[(.*?)\](cfg[0-9]+)\*\/}', $v, $mt)){
   $body .= '<tr style="background:#fff;">'.NL.'<td id="'.$mt[2].'" style="padding-left:.5em;" colspan="2"  class="igreen">■ '.$mt[1].'</td>'.NL.'</tr>'.NL;
  }
 }

 $body .= '
 </table>
  <p class="center" style="margin: 1em auto;">
  <input type="image" src="Images/reload1.png" title="更 新"
    onmouseover="this.src=\'Images/reload2.png\';"
    onmouseout="this.src=\'Images/reload1.png\'" alt="Refresh"/>
  </p>
 </fieldset>
 </form>
 ';
}

return $DIVISION['body'] .= $header.$body;
?>
